#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>

struct Cmd {
  int argc;
  char *argv[16];
} cmd;

void init_cmd(){  //初始化
  cmd.argc = 0;
  for(int i=0;i<16;i++){cmd.argv[i] = NULL;}
}

void cut_str(char *command){
  init_cmd();
  char *str = (char*)malloc(sizeof(command));
  strcpy(str,command);
  cmd.argv[cmd.argc] = strtok(str," \n");
  while(cmd.argv[cmd.argc] != NULL){
    cmd.argc++;
    cmd.argv[cmd.argc] = strtok(NULL," \n");
  }
}

void read_pipe(char *command){
  init_cmd();
  cut_str(command);
  /* printf("argc: %d\n",cmd.argc);
  for(int i=0;i<=cmd.argc;i++){
    printf("argv[%d]: %s\n",cmd.argc,cmd.argv[i]);
  } */
  int fd[2];
  char buf[256];
  pid_t pid;
  pipe(fd); 
  pid = fork(); 
  if (pid == 0){
    dup2(fd[1], 1);
    close(fd[0]);
    close(fd[1]);
    int error = execvp(cmd.argv[0], cmd.argv);
    if(error < 0) perror("execvp");
    exit(0);
  }
  dup2(fd[0], 0); 
  close(fd[0]);
  close(fd[1]);
  int count;
  while(count=read(0, buf, sizeof(buf))>0){
    printf("%s", buf);
  }
}

int main() {
    printf("--------------------------------------------------\n");
    read_pipe("echo HELLO WORLD");
    printf("--------------------------------------------------\n");
    read_pipe("ls /");
    printf("--------------------------------------------------\n");
    return 0;
}
